package io.finer.erp.jeecg.bas.service.impl;

import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;

import io.finer.erp.jeecg.bas.entity.BasMaterial;
import io.finer.erp.jeecg.bas.entity.BasMaterialCategory;
import io.finer.erp.jeecg.bas.entity.BasProductFormula;
import io.finer.erp.jeecg.bas.entity.ZrkDailyReportFh;
import io.finer.erp.jeecg.bas.entity.ZrkDailyReportQz;
import io.finer.erp.jeecg.bas.entity.ZrkParameters;
import io.finer.erp.jeecg.bas.entity.ZrkQzOrder;
import io.finer.erp.jeecg.bas.entity.ZzDevice;
import io.finer.erp.jeecg.bas.entity.ZzShoporder;
import io.finer.erp.jeecg.bas.mapper.ZrkDailyReportFhMapper;
import io.finer.erp.jeecg.bas.service.IBasMaterialCategoryService;
import io.finer.erp.jeecg.bas.service.IBasMaterialService;
import io.finer.erp.jeecg.bas.service.IBasProductFormulaService;
import io.finer.erp.jeecg.bas.service.IZrkDailyReportFhService;
import io.finer.erp.jeecg.bas.service.IZrkDailyReportFqService;
import io.finer.erp.jeecg.bas.service.IZrkDailyReportQzService;
import io.finer.erp.jeecg.bas.service.IZrkMesFqParamService;
import io.finer.erp.jeecg.bas.service.IZrkParametersService;
import io.finer.erp.jeecg.bas.service.IZrkQzOrderService;
import io.finer.erp.jeecg.bas.service.IZzDeviceService;
import io.finer.erp.jeecg.bas.service.IZzShoporderService;
import io.finer.erp.jeecg.bas.vo.ZrkParametersVO;
import io.finer.erp.jeecg.stock.entity.StkIoBill;
import io.finer.erp.jeecg.stock.entity.StkIoBillEntry;
import io.finer.erp.jeecg.stock.mapper.StkIoBillEntryMapper;
import io.finer.erp.jeecg.stock.mapper.StkIoBillMapper;
import io.finer.erp.jeecg.stock.service.IStkIoBillEntryService;
import io.finer.erp.jeecg.stock.service.IStkIoBillService;

/**
 * @Description: 复合报表
 * @Author: jeecg-boot
 * @Date:   2021-08-12
 * @Version: V1.0
 */
@Service
public class ZrkDailyReportFhServiceImpl extends ServiceImpl<ZrkDailyReportFhMapper, ZrkDailyReportFh> implements IZrkDailyReportFhService {

	@Autowired
	private IZrkParametersService zrkParametersService;
	@Autowired
	private IZrkDailyReportFhService fhService;
	@Autowired
	private IZrkDailyReportFqService fqService;
	@Autowired
	private IZrkDailyReportQzService qzService;
	@Autowired
	private IZzShoporderService shoporderService;
	@Autowired
	private IZrkMesFqParamService zrkMesFqParamService;
	@Autowired
	private IStkIoBillService billService;
	@Autowired
	private IStkIoBillEntryService entryService;
	@Autowired
	private StkIoBillMapper billMapper;
	@Autowired
	private StkIoBillEntryMapper entryMapper;
	@Autowired
	private IZrkQzOrderService qzOrderService;
	@Autowired
	private IZzDeviceService deviceService;
	@Autowired
	private ISysBaseAPI sysBaseAPI;
	@Autowired
	private IBasMaterialCategoryService categoryService;
	@Autowired
	private IBasMaterialService materialService;
	@Autowired
	private IBasProductFormulaService formulaService;
	
	
	@Override
	public boolean updateReportFh(ZrkDailyReportFh zrkDailyReportFh) {
		// TODO Auto-generated method stub
		//用胶量
		if(zrkDailyReportFh.getActualLength()!=null && zrkDailyReportFh.getActualGlueWeight()!=null
				&& oConvertUtils.isNotEmpty(zrkDailyReportFh.getWidth())) {
			BigDecimal glueSum = zrkDailyReportFh.getActualLength()
												.multiply(zrkDailyReportFh.getActualGlueWeight())
												.multiply(new BigDecimal(zrkDailyReportFh.getWidth()));
			zrkDailyReportFh.setGlueSum(glueSum);
		}
		//多涂胶克数
		if(zrkDailyReportFh.getGlueSum()!=null && oConvertUtils.isNotEmpty(zrkDailyReportFh.getMoreSquare())) {
			BigDecimal glueGrams = zrkDailyReportFh.getGlueSum().divide(new BigDecimal(zrkDailyReportFh.getMoreSquare()), 2, BigDecimal.ROUND_HALF_UP);
			zrkDailyReportFh.setGlueGrams(glueGrams);
		}
		//理论产量
		if(zrkDailyReportFh.getEndTime()!=null && zrkDailyReportFh.getStartTime()!=null && oConvertUtils.isNotEmpty(zrkDailyReportFh.getTheorySpeed())) {
			long times = (zrkDailyReportFh.getEndTime().getTime()-zrkDailyReportFh.getStartTime().getTime())/1000;
			BigDecimal theoryYield = new BigDecimal(String.valueOf(times)).multiply(new BigDecimal(zrkDailyReportFh.getTheorySpeed()));
			zrkDailyReportFh.setTheoryYield(theoryYield);
		}
		//效率
		if(zrkDailyReportFh.getTheoryYield()!=null && zrkDailyReportFh.getActualYield()!=null) {
			BigDecimal efficiency = zrkDailyReportFh.getActualYield().divide(zrkDailyReportFh.getTheoryYield(), 2, BigDecimal.ROUND_HALF_UP);
			zrkDailyReportFh.setEfficiency(String.valueOf(efficiency));
		}
		//面纸--底纸--成品-》浪费，后期维护上克重再作处理****************************************************************
		
		return this.updateById(zrkDailyReportFh);
	}

	@Override
	@Transactional
	public boolean saveReportFh(ZrkParametersVO zrkParametersVo) {
		// TODO Auto-generated method stub
		//查询主表数据
		ZrkQzOrder zrkQzOrder=qzOrderService.getById(zrkParametersVo.getProcessId());
//		List<ZrkParameters> zrkParametersList = zrkParametersService.selectByMainId(zrkParametersVo.getProcessId());
//		ZrkParameters zrkParameter = zrkParametersVo.get;
//		if(zrkParametersList!=null && zrkParametersList.size()>0) {
//			zrkParameter = zrkParametersList.get(0);
//		}
		//复合--添加复合日报表
		if(StringUtils.equals("1303963060735762433", zrkQzOrder.getProcessId())) {
			ZrkDailyReportFh fh = new ZrkDailyReportFh();
			fh.setFhSurfaceTension(zrkParametersVo.getFhSurfaceTension());
			fh.setFhPaperTension(zrkParametersVo.getFhPaperTension());
			fh.setFhWindingTension(zrkParametersVo.getFhWindingTension());
			if(oConvertUtils.isNotEmpty(zrkQzOrder.getMachineId())) {
				ZzDevice device = deviceService.getById(zrkQzOrder.getMachineId());
				if(device!=null) {
					fh.setMachineId(device.getDeviceName());
				}
			}
			if(oConvertUtils.isNotEmpty(zrkQzOrder.getOperatorUsers())) {
				String[] userIds = zrkQzOrder.getOperatorUsers().split(",");
				List<LoginUser> userList = sysBaseAPI.queryAllUserByIds(userIds);
				if(userList!=null && userList.size()>0) {
					StringBuffer users = new StringBuffer();
					for(LoginUser user:userList) {
						users.append(user.getRealname());
						users.append(",");
					}
					if(users!=null && users.length()>0) {
						fh.setOperatorUsers(users.toString().substring(0, users.toString().length()-1));
					}
				}
			}
			fh.setCustomerId(zrkQzOrder.getCustomerName());
			BasMaterialCategory category = categoryService.getById(zrkQzOrder.getMaterialId());
			if(category!=null) {
				fh.setMaterialId(category.getFullname());
			}
			BasProductFormula formula = formulaService.getById(zrkQzOrder.getFormulaId());
			if(formula!=null) {
				//品类-->配方
				fh.setCategoryId(formula.getPfName());
			}
			fh.setProductionDate(zrkQzOrder.getWoDeliverytime());//生产日期
			String[] orderIds =  zrkQzOrder.getOrderProcessId().split(",");
			List<String> orderList = Arrays.asList(orderIds);
			if(orderList!=null && orderList.size()>0) {
				List<ZzShoporder> shoporderList = shoporderService.listByIds(orderList);
				if(shoporderList!=null && shoporderList.size()>0) {
					//复合没有合单情况，取其中一条工单（没有关联不同销售订单的工单合单）
					ZzShoporder shoporder = shoporderList.get(0);
					fh.setOrderNo(shoporder.getOrderNo());
				}
			}
			if(oConvertUtils.isNotEmpty(zrkQzOrder.getSpecs())) {
				String[] model =  StringUtils.split(zrkQzOrder.getSpecs(), "*");
				if(oConvertUtils.isNotEmpty(model[0])) fh.setWidth(model[0]);
			}
			//涂胶方式
			fh.setGlueMethod(zrkParametersVo.getFhCoatingSurface());
			//复合物料
			List<String> materialids = billMapper.getMaterialIds(zrkQzOrder.getId(), "2991");
			List<BasMaterial> materialList = materialService.listByIds(materialids);
			if(materialList!=null && materialList.size()>0) {
				StringBuffer ids = new StringBuffer();
				for(BasMaterial material:materialList) {
					ids.append(material.getCode());
					ids.append(",");
				}
				if(ids!=null && ids.length()>0) {
					fh.setProductBarcode(ids.toString().substring(0, ids.toString().length()-1));
				}
			}
			return fhService.save(fh);
		}
		//切张--添加切张日报表
		if(StringUtils.equals("1300701144731623426", zrkQzOrder.getProcessId())
				|| StringUtils.equals("1300701196116041729", zrkQzOrder.getProcessId())) {
			ZrkDailyReportQz qz = new ZrkDailyReportQz();
			try {
				BeanUtils.copyProperties(qz, zrkQzOrder);
				BeanUtils.copyProperties(qz, zrkParametersVo);
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				e.printStackTrace();
			}
			if(oConvertUtils.isNotEmpty(zrkQzOrder.getMachineId())) {
				ZzDevice device = deviceService.getById(zrkQzOrder.getMachineId());
				if(device!=null) {
					qz.setMachineId(device.getDeviceName());
				}
			}
			if(oConvertUtils.isNotEmpty(zrkQzOrder.getOperatorUsers())) {
				String[] userIds = zrkQzOrder.getOperatorUsers().split(",");
				List<LoginUser> userList = sysBaseAPI.queryAllUserByIds(userIds);
				if(userList!=null && userList.size()>0) {
					StringBuffer users = new StringBuffer();
					for(LoginUser user:userList) {
						users.append(user.getRealname());
						users.append(",");
					}
					if(users!=null && users.length()>0) {
						qz.setUserWorkNo(users.toString().substring(0, users.toString().length()-1));
					}
				}
			}
			BasMaterialCategory category = categoryService.getById(zrkQzOrder.getMaterialId());
			if(category!=null) {
				qz.setMaterialId(category.getFullname());
			}
			BasProductFormula formula = formulaService.getById(zrkQzOrder.getFormulaId());
			if(formula!=null) {
				//品类-->配方
				qz.setCategoryId(formula.getPfName());
			}
			qz.setQzDate(zrkQzOrder.getWoDeliverytime());//生产日期
			String[] orderIds =  zrkQzOrder.getOrderProcessId().split(",");
			List<String> orderList = Arrays.asList(orderIds);
			if(orderList!=null && orderList.size()>0) {
				List<ZzShoporder> shoporderList = shoporderService.listByIds(orderList);
				if(shoporderList!=null && shoporderList.size()>0) {
					//若有合单的就取其中一条工单（没有关联不同销售订单的工单合单）
					ZzShoporder shoporder = shoporderList.get(0);
					qz.setOrderNo(shoporder.getOrderNo());
				}
			}
			if(oConvertUtils.isNotEmpty(zrkQzOrder.getSpecs())) {
				String[] model = zrkQzOrder.getSpecs().split("*");
				if(oConvertUtils.isNotEmpty(model[0])) qz.setWidth(model[0]);
				if(oConvertUtils.isNotEmpty(model[1])) qz.setLength(model[1]);
			}
			qz.setQty(zrkQzOrder.getProductNum());
			//品类-->配方
			qz.setCategoryId(zrkQzOrder.getFormulaId());
			//根据mes单查询切张生产出库信息，用过哪些料，找到上次用过该料的mes单
			List<String> materialids = billMapper.getMaterialIds(zrkQzOrder.getId(), "2993");
			LambdaQueryWrapper<StkIoBillEntry> query = new LambdaQueryWrapper<>();
			query.in(StkIoBillEntry::getMaterialId, materialids);
			List<StkIoBillEntry> entryList = entryService.list(query);
			List<String> billidList = Lists.newArrayList();
			if(entryList!=null && entryList.size()>0) {
				for(StkIoBillEntry entry:entryList) {
					billidList.add(entry.getMid());
				}
				//根据出入库id列表查询切张生产出库信息
				LambdaQueryWrapper<StkIoBill> queryWrap = new LambdaQueryWrapper<>();
				queryWrap.in(StkIoBill::getId, billidList);
				queryWrap.eq(StkIoBill::getStockIoType, "2993");
				queryWrap.eq(StkIoBill::getBillProcStatus, "23");
				List<String> mesIdList = Lists.newArrayList();//记录分切mes单id
				List<StkIoBill> billList = billService.list(queryWrap);
				if(billList!=null && billidList.size()>0) {
					for(StkIoBill bill:billList) {
						mesIdList.add(bill.getSourceId());
					}
					StringBuffer users = new StringBuffer();//上次切张此材料的分切员工
					List<ZrkQzOrder> qzOrderList = qzOrderService.listByIds(mesIdList);
					if(qzOrderList!=null && qzOrderList.size()>0) {
						for(ZrkQzOrder qzOrder:qzOrderList) {
							users.append(qzOrder.getOperatorUsers());
							users.append(",");
						}
						qz.setLastUser(users.substring(0, users.length()-1));
					}
				}
				//查询分切
				queryWrap = new LambdaQueryWrapper<>();
				queryWrap.in(StkIoBill::getId, billidList);
				queryWrap.eq(StkIoBill::getStockIoType, "1993");
				queryWrap.eq(StkIoBill::getBillProcStatus, "23");
				queryWrap.orderByDesc(StkIoBill::getCreateTime);
				List<StkIoBill> fqBillList = billService.list(queryWrap);
				if(fqBillList!=null && fqBillList.size()>0) {
					StkIoBill bill = fqBillList.get(0);
					//获取分切mes单
					ZrkQzOrder qzOrder = qzOrderService.getById(bill.getSourceId());
					qz.setFhWorkNo(qzOrder.getOperatorUsers());//复合机长工号->操作员
					qz.setFhBarcode(qzOrder.getMaterialId());//复合标签条码-->物料编号
					if(oConvertUtils.isNotEmpty(qzOrder.getSpecs())) {
						String[] model = qzOrder.getSpecs().split("*");
						if(oConvertUtils.isNotEmpty(model[0])) qz.setFqWidth(model[0]);
						if(oConvertUtils.isNotEmpty(model[1])) qz.setFqLength(model[1]);
					}
//					List<ZrkParameters> parmList = this.selectByMainId(qzOrder.getId());
//					if(parmList!=null && parmList.size()>0) {
//						ZrkParameters parm = parmList.get(0);
//						//复合涂胶方式
//						fq.setFhGlueMethod(parm.getFhCoatingSurface());
//						//复合卷向
//						fq.setFhVolume(parm.getFhVolume());
//					}
//					fq.setFhProductDate(qzOrder.getWoDeliverytime());//复合生产日期
					//外购材料来货日期/复合生产日期????此处稍后处理。。。。。。。。。。。。
					
					//分切平方数？？？？？
					
					
					
				}
				
			}
			//涂胶方式
//			qz.setGlueMethod(zrkParameters.getFhCoatingSurface());
			
			
//			return qzService.save(qz);
		}
		
		
		return false;
	}
	
}
